package com.zmn.oms.business.impl.invoice;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.zmn.base.invoice.dubbo.interfaces.manage.InvoiceInfoModifyRemoteService;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.reflect.BeanMapper;
import com.zmn.erp.dubbo.utils.DubboConsts;
import com.zmn.manager.mq.interfaces.ZmnMQSender;
import com.zmn.oms.business.interfaces.base.BaseCodeService;
import com.zmn.oms.business.interfaces.invoice.OrderInvoiceBService;
import com.zmn.oms.common.annotation.ZsNormalOrderWorkLog;
import com.zmn.oms.common.constant.ErpConsts;
import com.zmn.oms.common.constant.OrderConsts;
import com.zmn.oms.common.constant.OrderLogConsts;
import com.zmn.oms.common.constant.OrderStatusConsts;
import com.zmn.oms.common.dto.OmsOperator;
import com.zmn.oms.common.exception.OmsBaseException;
import com.zmn.oms.common.vo.KVDict;
import com.zmn.oms.constant.MessageQueueTopicConstant;
import com.zmn.oms.model.dto.invoice.InvoiceOperationNewDTO;
import com.zmn.oms.model.dto.invoice.InvoiceOperationRefundDTO;
import com.zmn.oms.model.dto.invoice.OrderInvoiceDTO;
import com.zmn.oms.model.entity.invoice.OrderInvoice;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.model.vo.invoice.OrderInvoiceVO;
import com.zmn.oms.services.interfaces.invoice.OrderInvoiceService;
import com.zmn.oms.services.interfaces.work.OrderWorkService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * 类描述：订单发票
 *
 * @author lujia
 * @date 2018/12/07 10:44
 */
@Service

public class OrderInvoiceBServiceImpl implements OrderInvoiceBService {

    private Logger logger = LoggerFactory.getLogger(OrderInvoiceBServiceImpl.class);

    @Autowired
    OrderInvoiceService orderInvoiceService;
    @Autowired
    OrderWorkService orderWorkService;
    @Resource
    ZmnMQSender zmnMQSender;
    @Resource
    private BaseCodeService baseCodeService;
    @org.apache.dubbo.config.annotation.Reference(version = DubboConsts.INTERFACE_VERSION, check = false)
    InvoiceInfoModifyRemoteService invoiceInfoModifyRemoteService;

    private static final String NEW_ORDER_TAG = "invoice_action_new_tag";
    private static final String REFUND_ORDER_TAG = "invoice_action_refund";



    @Override
    @ZsNormalOrderWorkLog(type = OrderLogConsts.ORDER_LOG_TYPE_INVOICE)
    public void saveInvoice(OrderInvoiceDTO orderInvoiceDTO) {
        OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderInvoiceDTO.getOrderId(), orderInvoiceDTO.getWorkId());

        if (Objects.equals(orderInvoiceDTO.getInvoiceNature(), ErpConsts.ORDER_INVOICE_TYPE_ELE)) {
            // 处理公司信息
            switch (orderWork.getPlatWork()) {
                case GlobalConsts.PLAT_MARK_YEYX:
                    orderInvoiceDTO.setCompanyId(20000);
                    break;
                case GlobalConsts.PLAT_MARK_SAAS:
                    orderInvoiceDTO.setCompanyId(30000);
                    break;
                case GlobalConsts.PLAT_MARK_CNHB:
                    orderInvoiceDTO.setCompanyId(40000);
                    break;
                default:
                    orderInvoiceDTO.setCompanyId(10000);
                    break;
            }

            String mqTag = "";
            String content = new String();
            switch (orderWork.getType()) {
                case OrderConsts.ORDER_TYPE_NEW:
                    mqTag = NEW_ORDER_TAG;
                    InvoiceOperationNewDTO newDTO = BeanMapper.map(orderInvoiceDTO, InvoiceOperationNewDTO.class);
                    newDTO.setBillType(1);
                    newDTO.setCityId(orderWork.getCityId());
                    content = JSONObject.toJSONString(newDTO);
                    break;
                case OrderConsts.ORDER_TYPE_REFUND:
                    mqTag = REFUND_ORDER_TAG;
                    InvoiceOperationRefundDTO refundDTO = BeanMapper.map(orderInvoiceDTO, InvoiceOperationRefundDTO.class);
                    refundDTO.setOriginalBillId(orderWork.getOrderId());
                    content = JSONObject.toJSONString(Lists.newArrayList(refundDTO));
                    break;
                default:
                    break;
            }

            if (Objects.isNull(content)) {
                logger.info("work[{}],开发票content为空", orderInvoiceDTO.getWorkId());
            }

            String key = String.format("%s_%s_%s", "orderwork_invoice", DateUtil.getNowTimestamp(), String.valueOf(orderInvoiceDTO.getWorkId()));
            logger.info("#orderwork#invoice#sendMq key : {}", key);
            zmnMQSender.send(MessageQueueTopicConstant.ZMN_TOPIC_ERP, mqTag, key, content);

        }

        // OMS保存一份
        // 先删除之前的发票 再新增
        orderInvoiceService.deleteOrderInvoiceByKey(orderInvoiceDTO.getWorkId());

        OrderInvoice orderInvoice = new OrderInvoice();
        orderInvoice.setInvoiceId(orderWork.getWorkId());
        orderInvoice.setTitle(orderInvoiceDTO.getBuyer());
        orderInvoice.setTaxNumber(orderInvoiceDTO.getBuyerTaxNum());
        orderInvoice.setAmount(orderInvoiceDTO.getInvoiceAmount());
        orderInvoice.setCreater(orderInvoiceDTO.getOperator());
        BeanMapper.copy(orderInvoiceDTO, orderInvoice);
        orderInvoiceService.insertOrderInvoice(orderInvoice);
    }


    @Override
    public List<KVDict> getInvoiceTypeList(OrderWork orderWork) throws OmsBaseException {
        List<KVDict> invoiceTypeList = Lists.newArrayList();

        // // 发票所需参数billType
        // Integer billType = Objects.equals(orderWork.getType(), OrderConsts.ORDER_TYPE_NEW) ? ErpConsts.ORDER_INVOICE_BILL_TYPE_WORK : ErpConsts.ORDER_INVOICE_BILL_TYPE_REFUND;
        // com.zmn.common.dto2.ResponseDTO<List<InvoiceApplyDRO>>  responseDTO = invoiceApplyListRemoteService.listInvoiceApplyByBillId(orderWork.getOrderId(), billType);
		//
        // List<InvoiceApplyDRO> invoiceApplyDROS = responseDTO.getData();
		//
        // if (checkEleInvoiceTypeAuthority(orderWork, invoiceApplyDROS)) {
        //     invoiceTypeList.add(ErpConsts.getInvoiceType(ErpConsts.ORDER_INVOICE_TYPE_ELE));
        // }
        // if (checkPapInvoiceTypeAuthority(orderWork, invoiceApplyDROS)) {
        //     invoiceTypeList.add(ErpConsts.getInvoiceType(ErpConsts.ORDER_INVOICE_TYPE_PAP));
        // }
        return invoiceTypeList;
    }

    @Override
    public OrderInvoiceVO getOriginalInvoiceVO(OrderWork orderWork) throws OmsBaseException{
        OrderInvoiceVO orderInvoiceVO = new OrderInvoiceVO();

        OrderInvoice orderInvoice = orderInvoiceService.findOrderInvoiceByKey(orderWork.getWorkId());

        if (Objects.equals(orderWork.getType(), OrderConsts.ORDER_TYPE_REFUND) || (orderInvoice!= null && Objects.equals(orderInvoice.getInvoiceNature(),  ErpConsts.ORDER_INVOICE_TYPE_ELE))) {
            return orderInvoiceVO;

            // ResponseDTO<List<InvoiceApplyDRO>>  responseDTO = invoiceApplyListRemoteService.listInvoiceApplyByBillId(orderWork.getOrderId(), 1);
            // if (!responseDTO.isSuccess()) {
            //     throw new OmsBaseException("查询原单发票信息失败：" + responseDTO.getMessage());
            // }
            // if (CollectionUtil.isNullOrEmpty(responseDTO.getData())) {
            //     return orderInvoiceVO;
            // }
            // BeanMapper.copy(responseDTO.getData().get(0), orderInvoiceVO);
        } else {
            if (orderInvoice != null) {
                orderInvoiceVO.setInvoiceNature(orderInvoice.getInvoiceNature());
                orderInvoiceVO.setBuyer(orderInvoice.getTitle());
                orderInvoiceVO.setBuyerTaxNum(orderInvoice.getTaxNumber());
                orderInvoiceVO.setAmount(orderInvoice.getAmount());
                orderInvoiceVO.setNumber(orderInvoice.getNumber());
                orderInvoiceVO.setCompanyId(orderInvoice.getCompanyId());
            }
        }

        return orderInvoiceVO;
    }

    @Override
    public Integer getInvoiceMaxAmount(OrderWork orderWork) throws OmsBaseException {
        if (Objects.equals(orderWork.getType(), OrderConsts.ORDER_TYPE_REFUND)) {
            return 0;
            // // 获取可开发票余额
            // ResponseDTO<Integer> responseDTO = invoiceApplyListRemoteService.getRefundAmountByBillId(orderWork.getOrderId());
            // if (!responseDTO.isSuccess()) {
            //     throw new OmsBaseException("获取可开票金额失败：" + responseDTO.getMessage());
            // }
            // return responseDTO.getData();
        } else {
            if (orderWork.getStatus() >= OrderStatusConsts.WORK_STATUS_COMPLETE) {
                return orderWork.getTotalAmount();
            }
        }
        return null;
    }


    @Override
    public List<KVDict> getBuyerTaxNumSuggestList(String queryText) {
        List<KVDict> companys = Lists.newArrayList();

        // logger.info("通过发票抬头查询纳税人识别号 入参：{}", queryText);
        // ResponseDTO<List<TaxpayerDRO>> responseDTO = invoiceApplyListRemoteService.listTaxpayer(queryText);
        // logger.info("通过发票抬头查询纳税人识别号 出参：{}", JSON.toJSONString(responseDTO));
        // if (!responseDTO.isSuccess() || CollectionUtil.isNullOrEmpty(responseDTO.getData())) {
        //     return companys;
        // }
        // responseDTO.getData().forEach(taxpayerDRO -> {
        //     if (StringUtil.isNotBlank(taxpayerDRO.getTaxNum()) && StringUtil.isNotBlank(taxpayerDRO.getCompanyName())) {
        //         companys.add(new KVDict(taxpayerDRO.getTaxNum(), taxpayerDRO.getCompanyName()));
        //     }
        // });


        return companys;
    }

    @Override
    @ZsNormalOrderWorkLog(type = OrderLogConsts.ORDER_LOG_TYPE_INVOICE_REMIND)
    public void invoiceRemind(OmsOperator operator) throws OmsBaseException {
            ResponseDTO responseDTO = invoiceInfoModifyRemoteService.remindInvoice(operator.getOrderId(),operator.getWorkId());
            if (!responseDTO.isSuccess()) {
                throw new OmsBaseException("提醒开票失败，请稍后重试");
            }
    }
}
